package com.example.crm.service;

import com.example.crm.entity.Role;
import com.example.crm.entity.User;
import com.example.crm.repository.UserRepository;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lenovo
 */
@Service("userService")
public class IUserServiceImpl implements IUserService{
    @Resource
    private UserRepository userRepository;

    @Override
    public User login(String usrName, String usrPassword) {
        List<User> userList = userRepository.findByUsrNameAndUsrPassword(usrName, usrPassword);
        User user = userList.get(0);

        return user;
    }

    @Override
    public User getUserByUsrName(String usrName) {
        return userRepository.findUserByUsrName(usrName);
    }

    @Override
    public void saveUser(User user) {
        userRepository.save(user);
    }

    @Override
    public void deleteUser(Long usrId) {
        userRepository.deleteById(usrId);
    }

    @Override
    public User getUser(Long usrId) {
        return userRepository.getById(usrId);
    }

    @Override
    public Page<User> findUsers(String usrName, Long roleId, Pageable pageable) {
        Specification<User> specification = new Specification<User>(){
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if(usrName!=null && !usrName.equals("")){
                    predicates.add(criteriaBuilder.like(root.get("usrName"),"%"+usrName+"%"));
                }
                if(roleId!= null && roleId.longValue()!=0L){
                    Role role = new Role();
                    role.setRoleId(roleId);
                    predicates.add(criteriaBuilder.equal(root.get("role"),role));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return userRepository.findAll(specification,pageable);
    }

    @Override
    public String encryptPassword(Object plaintextPassword) throws IllegalArgumentException{
        String salt = "czkt";
        Md5Hash md5Hash = new Md5Hash(plaintextPassword,salt,2);
        return md5Hash.toString();
    }
}